#include <iostream>
#include <string>
#include <thread>


int v = 1;

void critical_selection(int change_v) {
	static std::mutex mutx;
	std::lock_guard<std::mutex> lock(mutx);

	v = change_v;

	std::cout << "to: " << v << std::endl;
}

void critical_section_unique_lock(int change_v) {
	static std::mutex mtx;
	std::unique_lock<std::mutex> lock(mtx);

	// 执行竞争操作
	v = change_v;
	std::cout << "changed to: " << v << std::endl;
	// 将锁进行释放
	lock.unlock();

	// 在此期间，任何人都可以抢夺 v 的持有权

	// 开始另一组竞争操作，再次加锁
	lock.lock();
	v += 1;
	std::cout << "lock again, changed to: " << v << std::endl;
}

int main()
{
	std::thread t1(critical_selection, 2);	
	std::thread t2(critical_selection, 3);	

	std::cout << v << std::endl;
	t1.join();
	t2.join();
	std::cout << v << std::endl;






	std::thread t3(critical_section_unique_lock, 20);	
	std::thread t4(critical_section_unique_lock, 30);	

	t3.join();
	t4.join();

	std::cout << v << std::endl;



	return 0;
}